package com.sheliduan.itlearning.common.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sheliduan.itlearning.common.aspect.ApiOperationLog;
import com.sheliduan.itlearning.common.aspect.AuthAccess;
import com.sheliduan.itlearning.common.domain.dos.*;
import com.sheliduan.itlearning.common.domain.mapper.ArticleCourseMapper;
import com.sheliduan.itlearning.common.domain.mapper.UserCollectMapper;
import com.sheliduan.itlearning.common.domain.mapper.UserMapper;
import com.sheliduan.itlearning.common.domain.mapper.VideoCourseMapper;
import com.sheliduan.itlearning.common.model.vos.*;
import com.sheliduan.itlearning.common.utils.PageResponseData;
import com.sheliduan.itlearning.common.utils.ResponseData;
import com.sheliduan.itlearning.common.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: 断舍离
 * @date: 2025/1/22 10:03
 * @description: 用户通用登录模块(管理员/博主/普通用户)共用
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    // 此处逻辑简单, 直接调用持久层, 中间不过渡业务层了
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserCollectMapper userCollectMapper;

    @Autowired
    private ArticleCourseMapper articleCourseMapper;

    @Autowired
    private VideoCourseMapper videoCourseMapper;

    /*
    * 登录
    * */
    @PostMapping("/login")
    @ApiOperationLog(description = "登录接口")
    @AuthAccess
    public ResponseData login(@RequestBody @Validated LoginRegisterReqVO reqVO){
        // 根据用户名和角色查找是否有对应的用户存在
        UserDO userDO = userMapper.findUserByUsernameAndRole(reqVO.getUsername(), reqVO.getRole());
        // 用户不存在
        if(userDO == null) {
            return ResponseData.fail("用户名或密码错误");
        }

        // 密码错误
        if(!userDO.getPassword().equals(reqVO.getPassword())){
            return ResponseData.fail("用户名或密码错误");
        }
        String token = TokenUtil.generateToken(userDO.getId().toString(), userDO.getPassword());
        // 构建用户信息VO对象
        FindUserInfoRspVO userInfoRspVO = FindUserInfoRspVO.builder()
                .id(userDO.getId())
                .username(userDO.getUsername())
                .role(userDO.getRole())
                .avatar(userDO.getAvatar())
                .token(token)
                .build();
        return ResponseData.success(userInfoRspVO);
    }

    /*
     * 注册
     * */
    @PostMapping("/register")
    @ApiOperationLog(description = "注册接口")
    @AuthAccess
    public ResponseData register(@RequestBody @Validated LoginRegisterReqVO reqVO){
        // 判断用户是否存在
        UserDO userDO = userMapper.findUserByUsername(reqVO.getUsername());
        if(userDO != null) {
            return ResponseData.fail("用户名已经存在");
        }

        userDO = UserDO.builder()
                .username(reqVO.getUsername())
                .password(reqVO.getPassword())
                .role(reqVO.getRole())
                .avatar("头像地址")
                .money(0.0)
                .createTime(new Date())
                .updateTime(new Date())
                .isDeleted(false)
                .build();
        userMapper.insert(userDO);
        return ResponseData.success();
    }

    /*
     * 修改用户信息
     * */
    @PostMapping("/updateUserInfo")
    @ApiOperationLog(description = "修改用户信息接口")
    @AuthAccess
    public ResponseData updateUserInfo(@RequestBody @Validated UpdateUserInfoReqVO reqVO) {
        // 修改用户信息
        userMapper.updateUserInfoById(reqVO.getId(), reqVO.getUsername(), reqVO.getAvatar());
        // 重新查找该用户
        UserDO userDO = userMapper.findUserByUsername(reqVO.getUsername());
        // 构建用户信息VO对象
        FindUserInfoRspVO userInfoRspVO = FindUserInfoRspVO.builder()
                .id(userDO.getId())
                .username(userDO.getUsername())
                .role(userDO.getRole())
                .avatar(userDO.getAvatar())
                .token(reqVO.getToken())
                .build();
        return ResponseData.success(userInfoRspVO);
    }

    @PostMapping("/updatePassword")
    @ApiOperationLog(description = "修改用户密码接口")
    @AuthAccess
    public ResponseData updatePassword(@RequestBody @Validated UpdatePasswordReqVO reqVO) {
        UserDO userDO = userMapper.findUserByUsername(reqVO.getUsername());
        if(!userDO.getPassword().equals(reqVO.getPassword())) {
            return ResponseData.fail("旧密码输入不正确");
        }
        // 修改新密码
        userMapper.updatePasswordByUsername(reqVO.getUsername(), reqVO.getNewPassword());
        return ResponseData.success();
    }

    @PostMapping("/collectCourse")
    @ApiOperationLog(description = "收藏课程")
    public ResponseData collectCourse(@RequestBody @Validated CollectCourseReqVO reqVO) {
        UserCollectDO userCollectDO = new UserCollectDO();
        userCollectDO.setCourseId(reqVO.getCourseId());
        userCollectDO.setType(reqVO.getType());
        userCollectDO.setUserId(reqVO.getUserId());
        userCollectMapper.insert(userCollectDO);
        return ResponseData.success();
    }

    @PostMapping("/cancelCollectCourse")
    @ApiOperationLog(description = "取消收藏课程")
    public ResponseData cancelCollectCourse(@RequestBody @Validated CollectCourseReqVO reqVO) {
        LambdaQueryWrapper<UserCollectDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCollectDO::getUserId, reqVO.getUserId());
        wrapper.eq(UserCollectDO::getCourseId, reqVO.getCourseId());
        wrapper.eq(UserCollectDO::getType, reqVO.getType());
        userCollectMapper.delete(wrapper);
        return ResponseData.success();
    }

    @PostMapping("/isCollected")
    @ApiOperationLog(description = "查询课程是否已收藏")
    public ResponseData isCollected(@RequestBody @Validated CollectCourseReqVO reqVO) {
        LambdaQueryWrapper<UserCollectDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCollectDO::getUserId, reqVO.getUserId());
        wrapper.eq(UserCollectDO::getCourseId, reqVO.getCourseId());
        wrapper.eq(UserCollectDO::getType, reqVO.getType());
        UserCollectDO collect = userCollectMapper.selectOne(wrapper);
        return ResponseData.success(collect != null);
    }

    @PostMapping("/findCollectPageList")
    @ApiOperationLog(description = "分页查询用户收藏的课程")
    public PageResponseData findCollectPageList(@RequestBody @Validated FindCollectPageListReqVO reqVO) {
        Integer userId = reqVO.getUserId();
        long current = reqVO.getCurrent();
        long size = reqVO.getSize();
        Page<UserCollectDO> page = userCollectMapper.selectPageList(current, size, userId);
        // 3. 获取收藏记录列表
        List<UserCollectDO> records = page.getRecords();
        List<FindCourseListRspVO> resultList = new ArrayList<>();
        
        // 4. 遍历收藏记录，根据类型查询对应的课程信息
        for (UserCollectDO collect : records) {
            FindCourseListRspVO courseVO = new FindCourseListRspVO();
            courseVO.setId(collect.getCourseId());
            courseVO.setType(collect.getType());
            // 根据类型查询不同表
            if (collect.getType() == 0) {
                // 图文课程
                ArticleCourseDO articleCourseDO = articleCourseMapper.selectById(collect.getCourseId());
                if (articleCourseDO != null) {
                    courseVO.setTitle(articleCourseDO.getTitle());
                    courseVO.setCover(articleCourseDO.getCover());
                    courseVO.setPrice(articleCourseDO.getPrice());
                    courseVO.setSummary(articleCourseDO.getSummary());
                    courseVO.setUsername(userMapper.selectById(articleCourseDO.getUserId()).getUsername());
                    courseVO.setType(articleCourseDO.getType());
                    courseVO.setStatus(articleCourseDO.getStatus());
                    courseVO.setWatchNums(articleCourseDO.getWatchNums());
                    courseVO.setCreateTime(articleCourseDO.getCreateTime());
                }
            } else {
                // 视频课程
                VideoCourseDO videoCourseDO = videoCourseMapper.selectById(collect.getCourseId());
                if (videoCourseDO != null) {
                    courseVO.setTitle(videoCourseDO.getTitle());
                    courseVO.setCover(videoCourseDO.getCover());
                    courseVO.setPrice(videoCourseDO.getPrice());
                    courseVO.setSummary(videoCourseDO.getSummary());
                    courseVO.setUsername(userMapper.selectById(videoCourseDO.getUserId()).getUsername());
                    courseVO.setType(videoCourseDO.getType());
                    courseVO.setStatus(videoCourseDO.getStatus());
                    courseVO.setWatchNums(videoCourseDO.getWatchNums());
                    courseVO.setCreateTime(videoCourseDO.getCreateTime());
                }
            }
            resultList.add(courseVO);
        }
        
        // 5. 构建返回结果
        return PageResponseData.success(page, resultList);
    }

    @GetMapping("/test")
    @ApiOperationLog(description = "测试接口")
    public ResponseData test(){
        return ResponseData.success("测试数据");
    }

}
